<?php
/**
 * Description: 题型判定作业模块
 * User: devforma
 * Date: 16/7/29
 * Time: 12:05
 */

require __DIR__ . '/ProcessExerciseBase.class.php';

class TixingpandingModule extends ProcessExerciseBase {

    function __construct($exerciseType) {
        parent::__construct();
        $this->data['exercise_type'] = (int)$exerciseType;
    }

    /**
     * 设置作业类型
     */
    protected function setExerciseType() {
        return;
    }

    /**
     * 设置作业题目
     */
    protected function setExerciseQuestion() {
        global $cmsdb;

        //获取题目信息
        $qids = implode(',', $this->questionIds);
        $sql  = "SELECT * FROM `original_primary_question` WHERE `id` IN ({$qids}) ORDER BY FIELD (`id`, {$qids})";
        $questions = $cmsdb->getResults($sql);

        $data = [];
        foreach ($questions as $question) {

            //随机生成四个选项,包含正确答案
            $options = explode('#', $question->options);
            if (empty($options[0])) unset($options[0]);

            $selectedOpts = [];
            foreach ($options as $option) {
                $selectedOpts[] = $option;
            }

            $originZtkQuestionsInfo = VipUtils::getOriginalZtkQuestions($question->content);

            $data[] = [
                'question_id' => (int)$question->id,
                'question'    => $originZtkQuestionsInfo->question,
                'material'    => $originZtkQuestionsInfo->material,
                'options'     => $selectedOpts,
                'answer'      => $question->right_answer
            ];
        }

        $this->data['question'] = $data;
    }

    /**
     * 设置提交权限
     */
    protected function setSubmitPriv() {
        parent::setSubmitPriv();
    }

    /**
     * 设置用户答案
     */
    protected function setUserAnswer() {
        global $uddb;

        //查询用户做题记录
        $sql = 'SELECT * FROM `history_user_primary_question` WHERE `exercise_id`=:eid AND `user_id`=:uid';
        $records = $uddb->getResults($sql, [':eid' => $this->exerciseId, ':uid' => $this->userId]);
        $answers = [];
        foreach ($records as $r) {
            $answers[$r->question_id] = [
                'is_right' => (bool)$r->is_right,
                'answer'   => $r->user_answer
            ];
        }

        //合并用户答案
        foreach ($this->data['question'] as &$question) {
            $question['user_answer'] = $answers[$question['question_id']];
        }
    }

    /**
     * 设置作业的统计信息
     */
    protected function setSummary() {
        $this->data['summary'] = json_decode($this->userExerciseRecord->summary);
    }


    /**
     * 检测提交的参数
     * @param array $args 参数
     * @return bool
     */
    public function validateArgs($args) {
        if (!empty($args['answer_content']) && !empty($args['duration'])) {
            $this->submitArgs = $args;
            return true;
        }

        return false;
    }

    /**
     * 提交 - 设置作业状态
     */
    protected function setSubmitStatus() {
        if ($this->exerciseInfo->end_time > $this->now)
            $this->submitExerciseRecord['status'] = 1; //已完成
        else
            $this->submitExerciseRecord['status'] = 5; //过期完成
    }

    /**
     * 提交 - 保存答题记录及设置作业统计信息
     */
    protected function saveQuestionRecordsAndSetSubmitSummary() {
        global $uddb;

        $answers = json_decode($this->submitArgs['answer_content']);

        $total = $right = 0;   //题目总数和答对数
        foreach ($answers as $q) {
            if ($q->is_right)
                $right++;

            $total++;

            //构造数据结构
            $questionRecord = [
                'question_id' => $q->question_id,
                'exercise_id' => $this->exerciseId,
                'user_id'     => $this->userId,
                'acting_time' => $this->now,
                'user_answer' => $q->answer,
                'is_right'    => $q->is_right,
                'status'      => 1
            ];

            $uddb->insert('history_user_primary_question', $questionRecord);
        }

        //更新已做人数
        $this->updateXingcePersonsNum();

        if ($total == $right && $right != 0) {

            //记录是第几个完成作业的人
            VipUtils::setRanking($this->submitArgs);

            //返回值格式
            $this->submitArgs['is_arr'] = 2;
            //作业类型
            $this->submitArgs['type_id'] = $this->exerciseInfo->type_id;

            //更新全站通关最快时间
            $fastest = VipUtils::getFastest($this->submitArgs);
            if (empty($fastest) || $fastest >= $this->submitArgs['duration'])
                VipUtils::setFastest($this->submitArgs);


            //更新个人通关最快时间
            $fastestSelf = VipUtils::getFastestSelf($this->submitArgs);
            if (empty($fastestSelf) || $fastestSelf >= $this->submitArgs['duration'])
                VipUtils::setFastestSelf($this->submitArgs);

        }
        $ranking = VipUtils::getRanking($this->submitArgs);

        //保存统计信息
        $this->submitExerciseRecord['summary'] = json_encode([
            'position'     => $this->getXingcePersonsNum(),
            'duration'     => (int)$this->submitArgs['duration'],
            'accuracy'     => round($right/$total, 3),
            'avg_duration' => round($this->submitArgs['duration']/$total),
            'ranking'      => $ranking
        ]);
    }

    /**
     * 获取自测题目
     *
     * @param array $ids
     * @param array $userAnswers
     * @return array
     */
    protected function getSelfTestQuestions($ids, &$userAnswers) {
        global $cmsdb;

        //获取题目信息
        $qids = implode(',', $ids);
        $sql  = "SELECT * FROM `original_primary_question` WHERE `id` IN ({$qids}) ORDER BY FIELD (`id`, {$qids})";
        $questions = $cmsdb->getResults($sql);

        $data = [];
        foreach ($questions as $question) {

            $options = explode('#', $question->options);
            if (empty($options[0])) unset($options[0]);

            $selectedOpts = [];
            foreach ($options as $option) {
                $selectedOpts[] = $option;
            }

            if (isset($userAnswers[$question->id])) { //做题报告取题
                $data[] = [
                    'question_id' => (int)$question->id,
                    'question'    => $question->content,
                    'options'     => $selectedOpts,
                    'answer'      => $question->right_answer,
                    'user_answer' => $userAnswers[$question->id]
                ];

            } else {
                $data[] = [
                    'question_id' => (int)$question->id,
                    'question'    => $question->content,
                    'options'     => $selectedOpts,
                    'answer'      => $question->right_answer
                ];
            }
        }

        return $data;
    }

    /**
     * 提交自测题目
     *
     * @param array $args
     * @return array
     */
    public function submitSelfTest($args) {
        global $uddb;

        $answers = json_decode($args['answer_content']);

        $total = $right = 0;   //题目总数和答对数
        $records = [];
        foreach ($answers as $q) {
            if ($q->is_right)
                $right++;

            $total++;

            //构造数据结构
            $questionRecord = [
                'question_id' => $q->question_id,
                'exercise_id' => 0,
                'user_id'     => $args['user_id'],
                'acting_time' => $this->now,
                'user_answer' => $q->answer,
                'is_right'    => $q->is_right,
                'status'      => 1
            ];

            $uddb->insert('history_user_primary_question', $questionRecord);

            $records[] = $uddb->lastInsertId();
        }

        $summary = [
            'duration'     => (int)$args['duration'],
            'accuracy'     => round($right/$total, 3),
            'avg_duration' => round($args['duration']/$total)
        ];

        //自测记录
        $uddb->insert('history_user_primary_selftest', [
            'user_id'     => $args['user_id'],
            'type_id'     => $this->data['exercise_type'],
            'action_time' => $this->now,
            'records'     => implode(',', $records),
            'summary'     => json_encode($summary)
        ]);

        $summary['selftest_id'] = (int)$uddb->lastInsertId();

        //更新最快时间
        if ($total == $right && $right != 0) {

            $args['is_arr'] = 2;
            $fastest        = VipUtils::getFastest($args);
            $fastestSelf    = VipUtils::getFastestSelf($args);

            //更新个人通关最快时间
            if (empty($fastestSelf) || $fastestSelf >= $args['duration'])
                VipUtils::setFastestSelf($args);


            //更新全站通关最快时间
            if (empty($fastest) || $fastest >= $args['duration'])
                VipUtils::setFastest($args);

        }

        //保存统计信息
        return $summary;
    }

}